/*
 *    Copyright © OpenAtom Foundation.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package com.inspur.edp.bef.engine.repository.adaptor;

import com.inspur.edp.bef.bizentity.GspBizEntityObject;
import com.inspur.edp.cef.api.repository.DbParameter;
import com.inspur.edp.cef.api.repository.GspDbDataType;
import com.inspur.edp.cef.repository.dac.EntityDac;
import com.inspur.edp.cef.repository.sqlgenerator.BaseSqlGenerator;
import com.inspur.edp.cef.repository.sqlgenerator.PgSqlGenerator;

import java.sql.SQLException;
import java.util.List;

public class BefPgAdaptor extends BefBaseAdaptor{

    public BefPgAdaptor(GspBizEntityObject bizEntityObject, EntityDac entityDac) {
        super(bizEntityObject,entityDac);
    }

    @Override
    protected BaseSqlGenerator getSqlGenerator() {
        return new PgSqlGenerator();
    }

    public void deleteByParent(String joinInfo, String filter, List<DbParameter> dbPars) {
        String idWithAlias = this.getTableAlias() + "." + this.getPrimaryKey();
        if(getLogicDeleteInfo().isEnableLogicDelete()){
            dbPars.add(buildParam(getLogicDeleteInfo().getLabelId(), GspDbDataType.Char, "1"));
            executeSql(String.format("update %1$s set %2$s = ?%8$s WHERE %3$s IN ( SELECT %4$s FROM %5$s %6$s WHERE %7$s )"
                    , getTableName(), getLogicDeleteInfo().getLabelId(), idWithAlias, idWithAlias, getTableName(), joinInfo, filter, dbPars.size() - 1), dbPars);
        }
        else {
            this.executeSql(String.format("%1$s Where %2$s In (Select %2$s From %3$s %4$s Where %5$s)", this.getDeleteSql(), idWithAlias, this.getTableName(), joinInfo, filter), dbPars);
        }
    }
}
